package kratosplus

import (
	"strings"

	bm "github.com/go-kratos/kratos/pkg/net/http/blademaster"
	"github.com/go-kratos/kratos/pkg/net/metadata"

	"dbagent/pkg/util"
)

// GetToken 获取用户令牌
func GetToken(c *bm.Context) string {
	var token string
	auth := c.Request.Header.Get("Authorization")
	prefix := "Bearer "
	if auth != "" && strings.HasPrefix(auth, prefix) {
		token = auth[len(prefix):]
	}
	return token
}

// SetUID 给bm context设置用户id
func SetUID(ctx *bm.Context, uid string) {

	mid := util.Str2Int64(uid)
	ctx.Set(metadata.Mid, mid)
	if md, ok := metadata.FromContext(ctx); ok {
		md[metadata.Mid] = mid
		return
	}
}

// GetUID 从bm context获取用户id
func GetUID(ctx *bm.Context) (uid int64) {
	mid, ok := ctx.Get(metadata.Mid)
	if ok {
		return mid.(int64)
	}
	md, ok := metadata.FromContext(ctx)
	if ok {
		return md[metadata.Mid].(int64)
	}

	return 0
}
